<template>
  <a-select
    v-model:value="codeValue"
    allow-clear
    :placeholder="placeholder"
    :style="'width: ' + widthVal"
    show-search
    :filter-option="filterCodeOption"
    @change="handleChange"
  >
    <a-select-option
      v-for="item in trainList"
      :key="item.id"
      :label="item.code + item.start + item.end"
      :value="item.code"
    >
      {{ item.code }} {{ item.start }} - {{ item.end }}
    </a-select-option>
  </a-select>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { TrainApi } from '@/api/train';

const props = defineProps<{
  code: string;
  width?: string;
}>();

const placeholder = ref('请选择车次');
const codeValue = ref<string | null>('');
const widthVal = ref<string | null>('');
const trainList = ref<any[]>([]);

watch(
  () => props.code,
  newCode => {
    console.log('props', props);
    codeValue.value = newCode || null;
  },
  {
    immediate: true,
  }
);

watch(
  () => props.width,
  newWidth => {
    widthVal.value = newWidth || '100%';
  },
  {
    immediate: true,
  }
);

const emit = defineEmits<{
  (e: 'update:code', code: string): void;
}>();

onMounted(() => {
  getTrainList();
});

const getTrainList = async (): Promise<void> => {
  const { data } = await TrainApi.getTrainListAll();
  console.log(data);
  trainList.value = data || [];
};
// 结合show-search一块使用，以及定义label属性value属性，全量匹配所有的额外名称
const filterCodeOption = (input: string, option: any): boolean => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 返回选中值所在的对象集合
const handleChange = (code: string): void => {
  emit('update:code', code);
  const res = trainList.value.find(item => item.code === code);
  return res;
};
</script>
